<template>
  <div class="user-management-page">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="page-title">用户管理</h2>
      <p class="page-subtitle">管理系统中的所有用户信息</p>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon total">
            <el-icon><User /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-label">总用户数</div>
            <div class="stat-value">{{ users.length }}</div>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon admin">
            <el-icon><UserFilled /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-label">管理员</div>
            <div class="stat-value">{{ adminCount }}</div>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon normal">
            <el-icon><Avatar /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-label">普通用户</div>
            <div class="stat-value">{{ normalUserCount }}</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 搜索和筛选 -->
    <el-card class="filter-card" shadow="never">
      <div class="filter-content">
        <div class="filter-left">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索用户名、邮箱或手机号"
            prefix-icon="Search"
            clearable
            @input="handleSearch"
            class="search-input"
          />
        </div>
        <div class="filter-right">
          <el-button @click="refreshUsers" :loading="loading">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 用户卡片网格 -->
    <div class="users-grid" v-loading="loading">
      <el-card
        v-for="user in filteredUsers"
        :key="user.user_id"
        class="user-card"
        shadow="hover"
      >
        <div class="user-card-header">
          <div class="user-avatar">
            <img
              :src="user.avatar || defaultAvatar"
              :alt="user.username"
              @error="handleAvatarError"
            />
          </div>
          <div class="user-basic-info">
            <h3 class="user-name">{{ user.full_name || user.username }}</h3>
            <p class="user-username">@{{ user.username }}</p>
            <el-tag
              :type="user.role === 'admin' ? 'danger' : 'primary'"
              size="small"
            >
              {{ user.role === 'admin' ? '管理员' : '普通用户' }}
            </el-tag>
          </div>
        </div>

        <div class="user-card-content">
          <div class="user-info-item" v-if="user.email">
            <el-icon class="info-icon"><Message /></el-icon>
            <span class="info-text">{{ user.email }}</span>
          </div>
          <div class="user-info-item" v-if="user.phone_number">
            <el-icon class="info-icon"><Phone /></el-icon>
            <span class="info-text">{{ user.phone_number }}</span>
          </div>
          <div class="user-info-item">
            <el-icon class="info-icon"><Calendar /></el-icon>
            <span class="info-text">注册于 {{ formatDate(user.created_at) }}</span>
          </div>
        </div>

        <div class="user-card-actions">
          <el-button
            type="primary"
            size="small"
            @click="editUser(user)"
            :disabled="user.role === 'admin' && user.user_id !== currentUserId"
          >
            <el-icon><Edit /></el-icon>
            编辑
          </el-button>
          <el-button
            type="danger"
            size="small"
            @click="deleteUser(user)"
            :disabled="user.role === 'admin'"
          >
            <el-icon><Delete /></el-icon>
            删除
          </el-button>
        </div>
      </el-card>
    </div>

    <!-- 空状态 -->
    <div v-if="filteredUsers.length === 0 && !loading" class="empty-state">
      <el-empty description="暂无用户数据">
        <el-button type="primary" @click="refreshUsers">
          刷新数据
        </el-button>
      </el-empty>
    </div>
    <!-- 编辑用户对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEditing ? '编辑用户信息' : '查看用户信息'"
      width="500px"
      @close="handleClose"
    >
      <div class="dialog-content">
        <div class="user-avatar-section">
          <div class="avatar-preview">
            <img
              :src="form.avatar || defaultAvatar"
              alt="用户头像"
              @error="handleAvatarError"
            />
          </div>
        </div>

        <el-form
          ref="formRef"
          :model="form"
          :rules="formRules"
          label-width="80px"
          class="user-form"
        >
          <el-form-item label="用户名" prop="username">
            <el-input
              v-model="form.username"
              :disabled="!isEditing"
              placeholder="请输入用户名"
            />
          </el-form-item>

          <el-form-item label="密码" prop="password" v-if="isEditing">
            <el-input
              v-model="form.password"
              type="password"
              placeholder="留空则不修改密码"
              show-password
            />
          </el-form-item>

          <el-form-item label="真实姓名" prop="full_name">
            <el-input
              v-model="form.full_name"
              :disabled="!isEditing"
              placeholder="请输入真实姓名"
            />
          </el-form-item>

          <el-form-item label="邮箱地址" prop="email">
            <el-input
              v-model="form.email"
              :disabled="!isEditing"
              placeholder="请输入邮箱地址"
            />
          </el-form-item>

          <el-form-item label="手机号码" prop="phone_number">
            <el-input
              v-model="form.phone_number"
              :disabled="!isEditing"
              placeholder="请输入手机号码"
            />
          </el-form-item>

          <el-form-item label="用户角色" prop="role" v-if="isEditing">
            <el-select
              v-model="form.role"
              placeholder="选择用户角色"
              :disabled="form.user_id === currentUserId"
            >
              <el-option label="普通用户" value="user" />
              <el-option label="管理员" value="admin" />
            </el-select>
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">
            {{ isEditing ? '取消' : '关闭' }}
          </el-button>
          <el-button
            v-if="isEditing"
            type="primary"
            @click="handleSubmit"
            :loading="submitting"
          >
            保存修改
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from 'element-plus';
import { allUsersApi, deleteUserByIdApi, updateUserInfoApi } from "@/utils/api";
import {
  User,
  UserFilled,
  Avatar,
  Message,
  Phone,
  Calendar,
  Edit,
  Delete,
  Search,
  Refresh
} from '@element-plus/icons-vue';

// 响应式数据
const users = ref([]);
const loading = ref(false);
const dialogVisible = ref(false);
const isEditing = ref(true);
const submitting = ref(false);
const searchKeyword = ref('');
const formRef = ref(null);

// 默认头像
const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png';

// 当前用户ID
const currentUserId = JSON.parse(localStorage.getItem('user'))?.user_id;

// 表单数据
const form = ref({
  user_id: '',
  username: '',
  password: '',
  full_name: '',
  email: '',
  phone_number: '',
  role: 'user',
  avatar: ''
});

// 表单验证规则
const formRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone_number: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
};

// 计算属性
const adminCount = computed(() =>
  users.value.filter(user => user.role === 'admin').length
);

const normalUserCount = computed(() =>
  users.value.filter(user => user.role !== 'admin').length
);

const filteredUsers = computed(() => {
  if (!searchKeyword.value) return users.value;

  const keyword = searchKeyword.value.toLowerCase();
  return users.value.filter(user =>
    user.username?.toLowerCase().includes(keyword) ||
    user.full_name?.toLowerCase().includes(keyword) ||
    user.email?.toLowerCase().includes(keyword) ||
    user.phone_number?.includes(keyword)
  );
});

// 获取用户列表
const fetchUsers = async () => {
  try {
    loading.value = true;
    const response = await allUsersApi();
    users.value = response || [];
  } catch (error) {
    console.error("获取用户列表失败:", error);
    ElMessage.error('获取用户列表失败');
  } finally {
    loading.value = false;
  }
};

// 刷新用户列表
const refreshUsers = () => {
  fetchUsers();
};

// 搜索处理
const handleSearch = () => {
  // 搜索逻辑已在计算属性中处理
};

// 删除用户
const deleteUser = async (user) => {
  if (user.role === 'admin') {
    ElMessage.warning('不能删除管理员用户');
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除用户 "${user.username}" 吗？此操作不可恢复。`,
      '删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'el-button--danger'
      }
    );

    const response = await deleteUserByIdApi({ id: user.user_id });
    if (response.code === 200) {
      ElMessage.success('用户删除成功');
      await fetchUsers();
    } else {
      ElMessage.error(response.message || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error("删除用户失败:", error);
      ElMessage.error('删除用户失败');
    }
  }
};

// 编辑用户
const editUser = (user) => {
  form.value = {
    user_id: user.user_id,
    username: user.username,
    password: '',
    full_name: user.full_name || '',
    email: user.email || '',
    phone_number: user.phone_number || '',
    role: user.role || 'user',
    avatar: user.avatar || ''
  };

  isEditing.value = true;
  dialogVisible.value = true;
};

// 关闭对话框
const handleClose = () => {
  form.value = {
    user_id: '',
    username: '',
    password: '',
    full_name: '',
    email: '',
    phone_number: '',
    role: 'user',
    avatar: ''
  };
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();
    submitting.value = true;

    const updateData = {
      user_id: form.value.user_id,
      username: form.value.username,
      full_name: form.value.full_name,
      email: form.value.email,
      phone_number: form.value.phone_number
    };

    // 如果密码不为空，则包含密码更新
    if (form.value.password.trim()) {
      updateData.password = form.value.password;
    }

    const response = await updateUserInfoApi(updateData);
    if (response.code === 200) {
      ElMessage.success('用户信息更新成功');
      dialogVisible.value = false;
      await fetchUsers();
    } else {
      ElMessage.error(response.message || '更新失败');
    }
  } catch (error) {
    console.error("更新用户信息失败:", error);
    ElMessage.error('更新用户信息失败');
  } finally {
    submitting.value = false;
  }
};

// 头像加载错误处理
const handleAvatarError = (event) => {
  event.target.src = defaultAvatar;
};

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '未知';
  return new Date(dateStr).toLocaleDateString('zh-CN');
};

// 组件挂载时获取数据
onMounted(() => {
  fetchUsers();
});
</script>

<style lang="less" scoped>
.user-management-page {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 120px);
}

.page-header {
  margin-bottom: 24px;

  .page-title {
    font-size: 24px;
    font-weight: 600;
    color: #303133;
    margin: 0 0 8px 0;
  }

  .page-subtitle {
    color: #909399;
    margin: 0;
    font-size: 14px;
  }
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.stat-card {
  border: none;
  border-radius: 12px;
  overflow: hidden;

  :deep(.el-card__body) {
    padding: 20px;
  }

  .stat-content {
    display: flex;
    align-items: center;
    gap: 16px;
  }

  .stat-icon {
    width: 50px;
    height: 50px;
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 20px;
    color: white;

    &.total {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    }

    &.admin {
      background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
    }

    &.normal {
      background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
    }
  }

  .stat-info {
    flex: 1;

    .stat-label {
      font-size: 14px;
      color: #909399;
      margin-bottom: 4px;
    }

    .stat-value {
      font-size: 24px;
      font-weight: 600;
      color: #303133;
    }
  }
}

.filter-card {
  margin-bottom: 20px;
  border: none;

  :deep(.el-card__body) {
    padding: 16px 20px;
  }
}

.filter-content {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .filter-left {
    display: flex;
    gap: 16px;
    align-items: center;

    .search-input {
      width: 300px;
    }
  }

  .filter-right {
    display: flex;
    gap: 12px;
  }
}

.users-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.user-card {
  border: none;
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-4px);
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
  }

  :deep(.el-card__body) {
    padding: 20px;
  }
}

.user-card-header {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 16px;

  .user-avatar {
    width: 60px;
    height: 60px;
    border-radius: 50%;
    overflow: hidden;
    flex-shrink: 0;

    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }

  .user-basic-info {
    flex: 1;

    .user-name {
      font-size: 16px;
      font-weight: 600;
      color: #303133;
      margin: 0 0 4px 0;
    }

    .user-username {
      font-size: 14px;
      color: #909399;
      margin: 0 0 8px 0;
    }
  }
}

.user-card-content {
  margin-bottom: 16px;

  .user-info-item {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 8px;

    &:last-child {
      margin-bottom: 0;
    }

    .info-icon {
      color: #909399;
      font-size: 14px;
    }

    .info-text {
      font-size: 14px;
      color: #606266;
    }
  }
}

.user-card-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
  padding-top: 16px;
  border-top: 1px solid #f0f2f5;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  background: white;
  border-radius: 12px;
}

.dialog-content {
  .user-avatar-section {
    text-align: center;
    margin-bottom: 20px;

    .avatar-preview {
      width: 80px;
      height: 80px;
      border-radius: 50%;
      overflow: hidden;
      margin: 0 auto;
      border: 3px solid #f0f2f5;

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }
  }

  .user-form {
    .el-form-item {
      margin-bottom: 20px;
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

// 响应式设计
@media (max-width: 768px) {
  .user-management-page {
    padding: 16px;
  }

  .stats-cards {
    grid-template-columns: 1fr;
    gap: 16px;
  }

  .filter-content {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;

    .search-input {
      width: 100%;
    }
  }

  .users-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }

  .user-card-actions {
    flex-direction: column;

    .el-button {
      width: 100%;
    }
  }
}
</style>
